#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "err.hpp"

// 专注于实现套接字的各种功能（基于TCP协议）
namespace Yohifo
{
    static const int default_sock = -1;
    static const int backlog = 32;

    class Sock
    {
    public:
        Sock(int sock = default_sock) : _sock(sock)
        {
        }

        ~Sock()
        {
        }

        // 创建套接字
        void Socket()
        {
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock == -1)
            {
                logMessage(Fatal, "socket fail: %s", strerror(errno));
                exit(SOCKET_ERR);
            }
            logMessage(Debug, "socket success: %s", strerror(errno));
        }

        // 绑定网络信息
        void Bind(const uint16_t &port)
        {
            // 填充结构体
            struct sockaddr_in local;
            memset(&local, 0, sizeof local);

            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;

            // 绑定
            if (bind(_sock, (struct sockaddr *)&local, sizeof local) == -1)
            {
                logMessage(Fatal, "bind fail: %s", strerror(errno));
                exit(BIND_ERR);
            }
            logMessage(Debug, "bind success: %s", strerror(errno));
        }

        // 监听
        void Listen()
        {
            if (listen(_sock, backlog) == -1)
            {
                logMessage(Fatal, "listen fail: %s", strerror(errno));
                exit(LISTEN_ERR);
            }
            logMessage(Debug, "listen success: %s", strerror(errno));
        }

        // 接受连接（返回监听成功后的套接字）
        int Accept(std::string *ip, uint16_t *port)
        {
            struct sockaddr_in client;
            memset(&client, 0, sizeof client);

            socklen_t len = sizeof client;
            int sock = 0;
            if ((sock = accept(_sock, (struct sockaddr *)&client, &len)) < 0)
                logMessage(Error, "accept fail: %s", strerror(errno));
            else
            {
                //输出型参数
                *ip = inet_ntoa(client.sin_addr);
                *port = ntohs(client.sin_port);
                logMessage(Debug, "accept success: %s", strerror(errno));
            }

            return sock;
        }

        //连接（返回值用于判断是否连接成功）
        int Connect(const std::string &ip, const uint16_t &port)
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof server);

            server.sin_family = AF_INET;
            server.sin_port = htons(port);
            server.sin_addr.s_addr = inet_addr(ip.c_str());

            return connect(_sock, (struct sockaddr*)&server, sizeof server);
        }

        //获取套接字
        int getFd()
        {
            return _sock;
        }

        //关闭套接字
        void Close()
        {
            if(_sock != default_sock)
            {
                close(_sock);
                logMessage(Debug, "close sock: %s", strerror(errno));
            }
        }

    private:
        int _sock; // 套接字
    };
}